# -*- encoding: utf-8 -*-
"""
File Name: create_zabbix_dedicated_line_monitor_items
Description:
Author : 'lirui'
date: 2024/2/1
Contact: marjey_lee@163.com
Change Activity:
2024/2/1:
"""
from modules.blk.cmdb.common.cmdb_api import CMDBAPI
from modules.zabbix_utils.utils.zabbix_client import ZabbixClient


class CreateZabbixDedicatedLineMonitorItems:
    def __init__(
            self,
            ip='188.12.26.32',
            port=802,
            username='network',
            password='P@ssw0rd132'
    ):
        self.host_name = 'dedicated_line'
        self.client = ZabbixClient(
            ip=ip,
            port=port,
            username=username,
            password=password
        )
        self.base_url = 'http://189.12.16.41:902/dedicated_line'

    def _create_host(self):
        """

        """
        t = self.client.get_template('group', 'get_groups')
        t['params']['filter']['name'] = 'Discovered hosts'
        group_id = self.client.fetch(t)[0]['groupid']
        t = self.client.get_template('host', 'create_dedicated_line_host')
        t['params']['groups'][0]['groupid'] = group_id
        t['params']['host'] = self.host_name
        self.client.insert(t)

    @staticmethod
    def _load_cmdb():
        api = CMDBAPI()
        res = api.select_all('dedicated_line')
        data = res['data']['info']
        assert len(data) > 0
        return data

    def __call__(self):
        """

        Returns:

        """
        host_id = self._load_host_id()
        if host_id is None:
            self._create_host()
        host_id = self._load_host_id()
        self._create_items(host_id)

    def _create_items(self, host_id):
        """

        Args:
            host_id:

        Returns:

        """
        cmdb_data = self._load_cmdb()
        t = self.client.get_template(
            'items',
            'create_dedicated_line_http_proxy'
        )
        for data in cmdb_data:
            name = data['institution'] + '-' + data['opposite_ip_address']
            url = self.base_url + '/' + data['router'] + '/' + data['opposite_ip_address']
            t['params']['hostid'] = host_id
            t['params']['name'] = name
            t['params']['url'] = url
            t['params']['key_'] = f"Dedicated_line-{data['router']}-{data['opposite_ip_address']}"
            self.client.insert(t)

    def _load_host_id(self):
        t = self.client.get_template('host', 'get')
        t['params']['filter'] = {'host': [self.host_name]}
        content = self.client.fetch(t)
        if len(content) == 0:
            return None
        return content[0]['hostid']
